<template>
  <el-dialog v-bind="dialog" :visible.sync="dialog.visible" @close="close">
    <el-form ref="unbindEmailForm" :model="unbindEmailForm" :rules="formRules" label-position="top">
      <el-form-item> 请输入 {{ hideCharacter(userInfo.email, 'email') }} 收到的验证码完成解绑 </el-form-item>
      <el-form-item prop="code">
        <div class="flex">
          <el-input v-model="unbindEmailForm.code" size="medium" maxlength="6" type="text" name="code" placeholder="短信验证码" />
          <SendCode ref="sendUnbindcode" @run="sendUnbindCode" />
        </div>
      </el-form-item>
      <el-form-item align="right">
        <el-button type="primary" size="mini" @click="next">解 绑</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import { hideCharacter } from '@/utils'
import { validateMail } from '@/utils/validate.js'
import SendCode from '@/components/SendCode'
import { ucApi } from '@/api/api.js'

export default {
  components: {
    SendCode
  },
  data() {
    return {
      // 解绑
      unbindEmailForm: {
        code: ''
      },
      dialog: {
        visible: false,
        closeOnPressEscape: false,
        closeOnClickModal: false
      },
      formRules: {
        email: [
          { required: true, trigger: 'blur', message: '请输入邮箱' },
          { trigger: 'blur', validator: validateMail }
        ],
        code: [{ required: true, trigger: 'blur', message: '请输入邮件验证码' }]
      }
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
    hideCharacter() {
      return (value, type) => {
        return hideCharacter(value, type)
      }
    }
  },
  methods: {
    // 发送解绑验证码
    sendUnbindCode() {
      this.$request(ucApi.sendEmailCode, { email: this.userInfo.email, type: 1 }).then(() => {
        this.$refs.sendUnbindcode.start()
        this.$notify({
          title: '成功',
          message: '验证码已发送，请及时查收',
          //message: `${res.msg}`,
          type: 'success'
        })
      })
    },
    // 解绑
    next() {
      this.$refs.unbindEmailForm.validate(async (valid) => {
        if (valid) {
          try {
            const email = this.userInfo.email
            const { code } = this.unbindEmailForm
            await this.$request(ucApi.checkEmailCode, { email, code, type: 1 })
            await this.$request(ucApi.unbindEmail)
            this.$message({
              title: '提示',
              message: '解绑成功',
              type: 'success'
            })
            this.$store.dispatch('user/getInfo')
            this.dialog.visible = false
          } catch (error) {
            console.log(error)
          }
        }
      })
    },
    close() {
      this.$refs['unbindEmailForm'].resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.el-dialog__wrapper ::v-deep.el-dialog {
  max-width: 364px;
}
</style>
